package com.ruoyi.web.controller.shop.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.MemberRechargeConstants;
import com.ruoyi.common.constant.OrderConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.entity.DO.member.MemberBalanceRecordDO;
import com.ruoyi.common.entity.DO.member.MemberDO;
import com.ruoyi.common.entity.DO.order.OrderRefundDO;
import com.ruoyi.common.entity.DO.shop.ShopAppletDO;
import com.ruoyi.common.entity.VO.RefundVO;
import com.ruoyi.common.entity.VO.order.OrderRefundSearchVO;
import com.ruoyi.common.entity.wxpay.WxConfig;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.web.controller.member.mapper.IBackMemberBalanceRecordMapper;
import com.ruoyi.web.controller.member.mapper.IBackMemberMapper;
import com.ruoyi.web.controller.order.mapper.IBackMemberRechargeOrderMapper;
import com.ruoyi.web.controller.order.mapper.IBackOrderRefundMapper;
import com.ruoyi.web.controller.order.mapper.IBackShopPetrolOrderMapper;
import com.ruoyi.web.controller.shop.service.IBackShopAppletService;
import com.ruoyi.web.controller.shop.service.IBackShopOrderRefundService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 站点-退款订单管理
 */
@Controller
@RequestMapping("/back/shopOrderRefund")
public class BackShopOrderRefundController extends BaseController {
    private String prefix = "shop/order";

    @Resource
    private IBackShopOrderRefundService backShopOrderRefundService;

    @Resource
    private IBackOrderRefundMapper backOrderRefundMapper;

    @Resource
    private IBackMemberMapper backMemberMapper;

    @Resource
    private IBackShopAppletService shopAppletService;

    @Resource
    private IBackMemberRechargeOrderMapper backMemberRechargeOrderMapper;

    @Resource
    private IBackMemberBalanceRecordMapper backMemberBalanceRecordMapper;

    @Resource
    private IBackShopPetrolOrderMapper backShopPetrolOrderMapper;

    /**
     * 订单退款列表-页面
     *
     * @return
     */
    @RequiresPermissions("back:shopOrderRefund:list")
    @GetMapping()
    public String list() {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        return prefix + "/refundList";
    }

    /**
     * 订单退款列表（搜索）-数据处理
     *
     * @param orderRefundDO
     * @return
     */
    @RequiresPermissions("back:shopOrderRefund:list")
    @PostMapping("/searchList")
    @ResponseBody
    public TableDataInfo searchList(OrderRefundDO orderRefundDO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        startPage();
        orderRefundDO.setShopId(ShiroUtils.getShopId());
        List<OrderRefundDO> list = backShopOrderRefundService.searchList(orderRefundDO);
        return getDataTable(list);
    }

    @PostMapping("/notify/{shopId}")
    @ResponseBody
    public String notify(@PathVariable("shopId") Long shopId, HttpServletRequest request) {
        request.setAttribute("shopId", shopId);
        return backShopOrderRefundService.wxRefundNotifyHandle(request, "IBackShopOrderRefundService");
    }

    /**
     * 订单退款列表（搜索）-数据处理
     *
     * @param refundSn
     * @return
     */
    @RequiresPermissions("back:shopOrderRefund:refresh")
    @GetMapping("/refresh/{refundSn}")
    @ResponseBody
    public AjaxResult refresh(@PathVariable("refundSn") String refundSn) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        OrderRefundSearchVO orderRefundSearchVO = new OrderRefundSearchVO();
        orderRefundSearchVO.setRefundSn(refundSn);
        orderRefundSearchVO.setIsDelete(0);
        OrderRefundDO orderRefundInfo = backOrderRefundMapper.getRefundInfo(orderRefundSearchVO);
        if (orderRefundInfo == null) {
            return error("退款申请无效！");
        }
        //TODO:判断支付方式
        if (orderRefundInfo.getRefundWay() == OrderConstants.OrderPayWayEnum.WX_PAY.getValue()
                && orderRefundInfo.getRefundStatus() == OrderConstants.RefundStatusEnum.PRE_REFUND.getValue()
        ) {
            //TODO：查询店铺的appId和secret
            ShopAppletDO shopApplet = shopAppletService.getShopAppletInfoByShopId(orderRefundInfo.getShopId());
            if (shopApplet == null || shopApplet.getIsEnable() == null || shopApplet.getIsDelete() == 1) {
                throw new BusinessException("请重新开通该订单的商家小程序！");
            }
            if (shopApplet.getIsEnable() == 0) {
                throw new BusinessException("请先上架该订单的商家小程序！");
            }
            WxConfig wxConfig = new WxConfig();
            wxConfig.setAppID(shopApplet.getAppletAppId());
            wxConfig.setKey(shopApplet.getAppletPayKey());
            wxConfig.setMchID(shopApplet.getAppletMchId());
            try {
                wxConfig.setCertData(orderRefundInfo.getShopId());
            } catch (Exception e) {
                error("支付证书错误！");
            }
            Map<String, String> resultMap = backShopOrderRefundService.refresh(refundSn, wxConfig);
            if (resultMap.containsKey("err_code")) {
                String errCode = resultMap.get("err_code");
                switch (errCode) {
                    case "REFUNDNOTEXIST":
                        //待退款
                        backOrderRefundMapper.updateRefundStatusByRefundSn(refundSn, OrderConstants.RefundStatusEnum.PRE_REFUND.getValue());
                        break;
                }
            } else {
                //TODO:退款成功
                backOrderRefundMapper.updateRefundStatusByRefundSn(refundSn, OrderConstants.RefundStatusEnum.COMPLETE.getValue());
                if (orderRefundInfo.getOrderType() == OrderConstants.RefundOrderTypeEnum.MEMBER_RECHARGE_ORDER.getValue()) {
                    backMemberRechargeOrderMapper.updatePayStatusByOrderSn(orderRefundInfo.getRefundOrderSn(), OrderConstants.OrderPayStatusEnum.REFUND_SUCCESS.getValue());
                } else if (orderRefundInfo.getOrderType() == OrderConstants.RefundOrderTypeEnum.PETROL_ORDER.getValue()) {
                    backShopPetrolOrderMapper.updatePayStatusByOrderSn(orderRefundInfo.getRefundOrderSn(), OrderConstants.OrderPayStatusEnum.REFUND_SUCCESS.getValue());
                }
            }
        }
        return success();
    }

    /**
     * 订单退款-数据处理
     *
     * @param refundSn
     * @return
     */
    @Log(title = "店铺-订单退款管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("back:shopOrderRefund:refund")
    @GetMapping("/refund/{refundSn}")
    @ResponseBody
    public AjaxResult refundToMember(@PathVariable("refundSn") String refundSn) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        OrderRefundSearchVO orderRefundSearchVO = new OrderRefundSearchVO();
        orderRefundSearchVO.setRefundSn(refundSn);
        orderRefundSearchVO.setIsDelete(0);
        OrderRefundDO orderRefundInfo = backOrderRefundMapper.getRefundInfo(orderRefundSearchVO);
        if (orderRefundInfo == null) {
            return error("退款申请无效！");
        }
        //TODO:判断支付方式
        if (orderRefundInfo.getRefundWay() == OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue()
                && orderRefundInfo.getRefundStatus() == OrderConstants.RefundStatusEnum.PRE_REFUND.getValue()
        ) {
            //TODO:增加余额
            MemberDO memberInfo = backMemberMapper.selectByPrimaryKey(orderRefundInfo.getMemberId());
            MemberDO memberUpdate = new MemberDO();
            memberUpdate.setId(orderRefundInfo.getMemberId());
            memberUpdate.setBalance(memberInfo.getBalance().add(orderRefundInfo.getRefundAmount()));
            //TODO:余额变动记录
            MemberBalanceRecordDO memberBalanceRecordDO = new MemberBalanceRecordDO();
            memberBalanceRecordDO.setShopId(orderRefundInfo.getShopId());
            memberBalanceRecordDO.setMemberId(orderRefundInfo.getMemberId());
            memberBalanceRecordDO.setRecordSn(OrderConstants.SnPrefix.BALANCE_MEMBER.getValue() + DateUtils.dateTimeNow() + NumberUtils.generateCode(4));
            memberBalanceRecordDO.setType(MemberRechargeConstants.TypeEnum.SYSTEM_INSERT.getValue());
            memberBalanceRecordDO.setChangeType(MemberRechargeConstants.ChangeTypeEnum.INCREASE.getValue());
            memberBalanceRecordDO.setLinkModel(MemberRechargeConstants.LinkModelEnum.REFUND.getValue());
            memberBalanceRecordDO.setLinkSn(orderRefundInfo.getRefundOrderSn());
            memberBalanceRecordDO.setOldBalance(memberInfo.getBalance());
            memberBalanceRecordDO.setChangeBalance(orderRefundInfo.getRefundAmount());
            memberBalanceRecordDO.setCreateBy("取消加油订单自动退款");
            memberBalanceRecordDO.setCreateTime(new Date());
            memberBalanceRecordDO.setNewBalance(memberUpdate.getBalance());
            memberBalanceRecordDO.setRemark("订单退款成功,余额退回:" + orderRefundInfo.getRefundAmount() + "元"
                    + "，帐号余额：" + memberUpdate.getBalance() + "元"
                    + "，退款单号：" + orderRefundInfo.getRefundSn());
            backMemberBalanceRecordMapper.insertSelective(memberBalanceRecordDO);
            backMemberMapper.updateByPrimaryKeySelective(memberUpdate);
            backOrderRefundMapper.updateRefundStatusByRefundSn(orderRefundInfo.getRefundSn(), OrderConstants.RefundStatusEnum.COMPLETE.getValue());
            backShopPetrolOrderMapper.updatePayStatusByOrderSn(orderRefundInfo.getRefundOrderSn(), OrderConstants.OrderPayStatusEnum.REFUND_SUCCESS.getValue());
            return success();
        } else {
            ShopAppletDO shopApplet = shopAppletService.getShopAppletInfoByShopId(orderRefundInfo.getShopId());
            if (shopApplet == null || shopApplet.getIsEnable() == null || shopApplet.getIsDelete() == 1) {
                throw new BusinessException("请重新开通该订单的商家小程序！");
            }
            if (shopApplet.getIsEnable() == 0) {
                throw new BusinessException("请先上架该订单的商家小程序！");
            }
            WxConfig wxConfig = new WxConfig();
            wxConfig.setAppID(shopApplet.getAppletAppId());
            wxConfig.setKey(shopApplet.getAppletPayKey());
            wxConfig.setMchID(shopApplet.getAppletMchId());
            try {
                wxConfig.setCertData(orderRefundInfo.getShopId());
            } catch (Exception e) {
                error("支付证书错误！");
            }
            RefundVO refundVO = new RefundVO();
            refundVO.setOrderType(orderRefundInfo.getOrderType());
            refundVO.setPayCost(orderRefundInfo.getOrderPayCost());
            refundVO.setRefundAmount(orderRefundInfo.getRefundAmount());
            refundVO.setOrderSn(orderRefundInfo.getRefundOrderSn());
            refundVO.setRefundSn(orderRefundInfo.getRefundSn());
            refundVO.setPaySn(orderRefundInfo.getRefundPaySn());
            refundVO.setWxConfig(wxConfig);
            try {
                backShopOrderRefundService.refund(refundVO);
                return success();
            } catch (Exception e) {
                return error(e.getMessage());
            }
        }
    }


}
